/**
 * 日志存储
 * @author JackBean
 */
import log4js from 'log4js';
import fs from 'fs';
import path from 'path';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const logsDir = path.join(__dirname, '../logs');

// 确保日志目录存在
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir, { recursive: true });
}
const levels = {
    'trace':log4js.levels.TRACE,
    'debug':log4js.levels.DEBUG,
    'info':log4js.levels.INFO,
    'warn':log4js.levels.WARN,
    'error':log4js.levels.ERROR,
    'fatal':log4js.levels.FATAL,
}

log4js.configure({
    appenders:{
        console:{ type:'console' },
        info:{
            type: 'file', 
            filename: path.join(logsDir, 'all-logs.log'),
            maxLogSize: 10485760, // 10MB
            backups: 5,
            compress: true
        },
        error:{
            type: 'dateFile',
            filename: path.join(logsDir, 'error'),
            pattern: 'yyyy-MM-dd.log',
            alwaysIncludePattern: true, // 设置文件名称为 filename + pattern
            maxLogSize: 10485760, // 10MB
            backups: 10,
            compress: true
        },
        exception: {
            type: 'dateFile',
            filename: path.join(logsDir, 'exception'),
            pattern: 'yyyy-MM-dd.log',
            alwaysIncludePattern: true
        }
    },
    categories:{
        default:{ appenders: [ 'console' ], level: 'debug' },
        info:{
            appenders: [ 'info','console' ],
            level: 'info'
        },
        error:{
            appenders: [ 'error','console' ],
            level: 'error'
        },
        exception: {
            appenders: [ 'exception', 'console' ],
            level: 'error'
        }
    }
})


export default {
    debug : (content)=>{
        let logger = log4js.getLogger();
        logger.level = levels.debug;
        logger.debug(content);
    },
    info : (content)=>{
        let logger = log4js.getLogger('info');
        logger.level = levels.info;
        logger.info(content);
    },
    error : (content)=>{
        let logger = log4js.getLogger('error');
        logger.level = levels.error;
        logger.error(content);
    }
};